<template>
   <el-card style="height: 80px;">
        <el-form :inline="true" class="form">
            <el-form-item label="用户名：">
                <el-input placeholder="请输入搜索的用户名字" v-model="keyword"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :disabled="keyword?false:true" @click="search">搜索</el-button>
                <el-button type="primary" @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
   </el-card>
   <el-card style="margin: 10px 0;">
        <el-button type="primary" @click="addUser">添加用户</el-button>
        <el-button type="primary" :disabled="selectIdArr.length?false:true" @click="deleteSelectUser">批量删除</el-button>
        <!-- table展示用户的信息 -->
        <el-table style="margin: 10px 0;" border :data="userArr" @selection-change="selectChange">
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column label="#" align="center" type="index"></el-table-column>
            <el-table-column label="ID" align="center" prop="id"></el-table-column>
            <el-table-column label="用户名字" align="center" prop="username" show-overflow-tooltip></el-table-column>
            <el-table-column label="用户名称" align="center" prop="name" show-overflow-tooltip></el-table-column>
            <el-table-column label="用户角色" align="center" prop="roleName" show-overflow-tooltip></el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" width="300px">
                <template #="{row,$index}">
                    <el-button type="primary" size="small" icon="User" @click="setRole(row)">分配角色</el-button>
                    <el-button type="primary" size="small" icon="Edit" @click="updateUser(row)">编辑</el-button>
                    <el-popconfirm title="确定删除" width="260px" @confirm="deleteUser(row.id)">
                        <template #reference>
                            <el-button type="primary" size="small" icon="Delete">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页器 -->
        <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[5, 7, 9,]"
        :background="true"
        layout=" prev, pager, next, jumper,->, sizes, total,"
        :total="total"
        @current-change="getHasUser"
        @size-change="handler"
        />
   </el-card>
   <!-- 抽屉结构 -->
   <el-drawer v-model="drawer">
        <template #header>
        <h4>{{ userParams.id?'更新用户':'添加用户' }}</h4>
        </template>
        <template #default>
            <el-form :model="userParams" :rules="rules" ref="formRef">
                <el-form-item label="用户姓名" prop="username">
                    <el-input placeholder="请输入姓名" v-model="userParams.username"></el-input>
                </el-form-item>
                <el-form-item label="用户昵称" prop="name">
                    <el-input placeholder="请输入昵称" v-model="userParams.name" ></el-input>
                </el-form-item>
                <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
                    <el-input placeholder="请输入密码" v-model="userParams.password"></el-input>
                </el-form-item>
            </el-form>
        </template>
        <template #footer>
        <div style="flex: auto">
            <el-button @click="cancel">取消</el-button>
            <el-button type="primary" @click="save">确定</el-button>
        </div>
        </template>
    </el-drawer>
    <!-- 抽屉结构,用于某一个已有的账号进行职位分配 -->
    <el-drawer v-model="drawer1">
        <template #header>
        <h4>分配角色</h4>
        </template>
        <template #default>
            <el-form-item label="用户姓名">
                <el-input v-model="userParams.username" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="职位列表">
                <el-checkbox
                v-model="checkAll"
                :indeterminate="isIndeterminate"
                @change="handleCheckAllChange"
                >
                    全选
                </el-checkbox>
                <!-- 显示职位的复选框 -->
                <el-checkbox-group
                    v-model="userRole"
                    @change="handleCheckedCitiesChange"
                >
                    <el-checkbox v-for="(role,index) in allRole" :key="index" :label="role">
                    {{ role.roleName }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
        </template>
        <template #footer>
        <div style="flex: auto">
            <el-button @click="drawer1=false">取消</el-button>
            <el-button type="primary" @click="confirmClick">确定</el-button>
        </div>
        </template>
    </el-drawer>
</template>
<script setup lang="ts">
import { AllRole, AllRoleResponseData, Records, SetRoleData, User, UserResponseData } from '@/api/acl/user/type';
import { reqAddOrUpdateUser, reqAllRole, reqRemoveUser, reqSelectUser, reqSetUserRole, reqUserInfo } from '@/api/acl/user';
import { ref,onMounted, reactive, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import useLayOutSettingStore from '@/store/modules/setting';
//获取模版仓库
let settingStore=useLayOutSettingStore();

//定义响应式数据收集用户输入的关键字
let keyword=ref<string>('');


//控制顶部全选复选框
const isIndeterminate = ref(true)

//控制分配角色抽屉的显示与隐藏
let drawer1=ref<boolean>(false);
//收集顶部全选数据
const checkAll = ref(false)

let pageNo=ref<number>(1);
let pageSize=ref<number>(5);
//用户总个数
let total=ref<number>(0)
let userArr=ref<Records>([]);
//控制抽屉的显示与隐藏
let drawer=ref<boolean>(false);
//收集用户信息的响应式数据
let userParams=reactive<User>({
    username: '',
    name: '',
    password: '',
})
//获取form组件实例
let formRef=ref<any>();

//校验用户名
const validatorUsername=(rule: any, value: any, callback: any)=>{
    //用户名字|昵称长度至少5位
    if(value.trim().length>=5){
        callback();
    }
    else{
        callback(new Error("用户名至少5位"));
    }
}

const validatorName=(rule: any, value: any, callback: any)=>{
    //用户名字|昵称长度至少5位
    if(value.trim().length>=5){
        callback();
    }
    else{
        callback(new Error("用户昵称至少5位"));
    }
}
const validatorPassword=(rule: any, value: any, callback: any)=>{
    //用户名字|昵称长度至少5位
    if(value.trim().length>=6){
        callback();
    }
    else{
        callback(new Error("密码至少6位"));
    }
}

//表单校验的规则
const rules={
    username:[{required: true,trigger: 'blur',validator: validatorUsername}],
    name:[{required: true,trigger: 'blur',validator: validatorName}],
    password:[{required: true,trigger: 'blur',validator: validatorPassword}],
}
//存储全部的职位数据
let allRole=ref<AllRole>([]);

//当前用户已有的职位

let userRole=ref<any>([]);
//准备一个数组存储批量删除的ID
let selectIdArr=ref<any>([]);






onMounted(()=>{
    getHasUser();
})


//获取全部已有的用户信息
const getHasUser=async (pager=1)=>{
    //收集当前的页码
    pageNo.value=pager;
    let result:UserResponseData= await reqUserInfo(pageNo.value,pageSize.value,keyword.value);
    console.log("获取已有用户信息");
    console.log(result);
    if(result.code==200){
        total.value=result.data.total;
        userArr.value=result.data.records;
    }
}
//分页器下拉菜单自定义事件的回调
const handler=()=>{
    getHasUser();
}

//添加用户按钮
const addUser=()=>{
    //显示抽屉
    drawer.value=true;
    Object.assign(userParams,{
        id: '',
        username:'',
        name: '',
        password: '',
    }),
    //清除上一次的错误提示信息
    nextTick(()=>{
        formRef.value.clearValidate('username');
        formRef.value.clearValidate('name');
        formRef.value.clearValidate('password');
    })
}

//更新已有的用户按钮
const updateUser=(row:User)=>{
    //显示抽屉
    drawer.value=true
    //收集已有的账号信息
    Object.assign(userParams,row);
    nextTick(()=>{
        formRef.value.clearValidate('username');
        formRef.value.clearValidate('name');
    })
}
//保存按钮
const save=async ()=>{
    //点击保持按钮进行表单校验
    await formRef.value.validate();
    let result:any=await reqAddOrUpdateUser(userParams);
    console.log('更新或添加用户');
    console.log(result);
    if(result.code==200){
        drawer.value=false;
        ElMessage({
            type: 'success',
            message: userParams.id?'更新成功':'添加成功',
        })
        // getHasUser(userParams.id?pageNo.value:1);
        //浏览器自动刷新一次
        window.location.reload();
    }   
    else{
        drawer.value=false;
        ElMessage({
            type: 'error',
            message: userParams.id?'更新失败':'添加失败',
        })
    }
}

//取消按钮的回调
const cancel=()=>{
    //关闭抽屉
    drawer.value=false;
}

//分配角色按钮
const setRole=async (row:User)=>{
    
    
    //存储已有的用户的信息
    Object.assign(userParams,row);
    //发起请求获取全部的职位数据与已有的职位
    let result:AllRoleResponseData=await reqAllRole(userParams.id as number);
    console.log('职位数据')
    console.log(result);
    if(result.code==200){
        //存储全部职位
        allRole.value=result.data.allRolesList;
        //存储当前用户已有的职位
        userRole.value=result.data.assignRoles;
        //抽屉显示
        drawer1.value=true;
    }
}

//顶部复选框的全选事件
const handleCheckAllChange = (val: any) => {
    userRole.value=val?allRole.value:[];
    //不确定样式
    isIndeterminate.value = false
}

//底部全部复选框
const handleCheckedCitiesChange = (value:any) => {
  //顶部复选框的勾选数据
  checkAll.value = userRole.value.length==allRole.value.length;
  //不确定的样式
  isIndeterminate.value=!checkAll.value;
  
}

//确定按钮
const confirmClick=async ()=>{
    //收集参数
    let data :SetRoleData={
        userId:userParams.id as number,
        roleIdList:userRole.value.map((item: { id: any; })=>{
            return (item.id)
        }),
    }
   //分配用户职位
   let result:any=await reqSetUserRole(data);
   if(result.code==200){
    ElMessage.success("分配职位成功");
    //获取更新完毕用户的信息
    getHasUser(pageNo.value);
   }
   drawer1.value=false;
}

const deleteUser=async (userId: number)=>{
    let result=await reqRemoveUser(userId);
    if(result.code==200){
        ElMessage.success("删除成功");
        getHasUser(userArr.value.length>1?pageNo.value:pageNo.value-1);
    }
    else{
        ElMessage.error("删除失败");
    }
}

//table复选框勾选的时候会触发的事件
const selectChange=(val:any)=>{
    selectIdArr.value=val;
}

//批量删除
const deleteSelectUser=async ()=>{
    let idList=selectIdArr.value.map((item: { id: any; })=>item.id);
    //批量删除的请求
    let result:any=await reqSelectUser(idList);
    if(result.code==200){
        ElMessage.success("删除成功");
        getHasUser(userArr.value.length>1?pageNo.value:pageNo.value-1);
    }
    else{
        ElMessage.error("删除失败");
    }
}

//搜索按钮
const search=()=>{
    //根据关键字获取用户数据
    getHasUser();
    keyword.value='';
}
const reset=()=>{
    settingStore.refsh=!settingStore.refsh;

}




</script>
<style scoped>
.form{
    display: flex;
    justify-content: space-between;
    align-items: center
}
</style>